/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;
import java.net.*; 
import java.io.*;

public class Client {
    protected DataOutputStream out;
    public static void main (String [] args ) throws IOException { 
        int filesize=2022386; 
        int bytesRead;
        int currentTot = 0;
        try (Socket socket = new Socket("localhost",5217)) {
            System.out.println("Connecting to Server: "+socket);      
            Client c = new Client();
            
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String filename;
            System.out.print("Enter File Name :");
            filename=br.readLine();
            File transferFile = new File (filename);
            c.SendFile(socket,transferFile);
        }
    }
    
    public void SendFile(Socket s, File transferFile) throws IOException
    {
        FileInputStream fis = null;
        try {
            out = new DataOutputStream(s.getOutputStream());
            if(!transferFile.exists())
            {
                      System.out.println("File invalid");
                      out.writeUTF("Fileinvalid");
                      return;
            }
            else out.writeUTF("Filevalid");
            fis = new FileInputStream(transferFile);
            byte [] bytearray  = new byte [1024*10];
            BufferedInputStream bis = new BufferedInputStream(fis);
            int size= fis.available();
            
            int c=-1;
            System.out.println("Sending...");
            long start = System.currentTimeMillis();
            while((c = bis.read(bytearray,0,bytearray.length)) != -1)
            {
                      out.write(bytearray, 0, c);
                      size -= c;
                      System.out.printf("\b Remaining %.2f Kb ",(float)size/1024);
                      System.out.flush();
            }
            
            out.flush();
            out.close();
            fis.close();
            s.close();
            System.out.println("\nFile transfer complete in: "+(System.currentTimeMillis()-start)/1000 + " s.");
        } catch (FileNotFoundException ex) {
        }
    }
    
    
}
